#!/bin/bash

# get the kernel and initrd
URL_BASE="https://releases.rancher.com/os/latest"
VMLINUX="vmlinuz"
INITRD="initrd"

cd /tmp
curl -O -L "${URL_BASE}/${VMLINUX}"
curl -O -L "${URL_BASE}/${INITRD}"

# setup the host ready for kexec
PUBLIC_IPV4=$(wget -qO- http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/address)

if [ "$(ros config get rancher.environment.installer)" == "true" ] && ros --version &>/dev/null; then
	cat > cloud-config.yml <<EOF
#cloud-config
rancher:
  network:
    interfaces:
      eth0:
        address: $(ip -4 addr show dev eth0 | awk "/${PUBLIC_IPV4}/ {print \$2}")
        gateway: $(ip -o route get 1 | awk '{print $3}')
        dhcp: false
ssh_authorized_keys:
EOF
	while read -r KEY; do
		echo "  - ${KEY}" >> cloud-config.yml
	done < <(wget -qO- http://169.254.169.254/metadata/v1/public-keys; echo)
	yes | ros install -c cloud-config.yml -d /dev/vda
	exit 0
fi

export DEBIAN_FRONTEND=noninteractive
apt-get update && apt-get install -y kexec-tools ipcalc

PUBLIC_IPV4_NETMASK=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/netmask)
PUBLIC_IPV4_CIDR=$(ipcalc ${PUBLIC_IPV4}/${PUBLIC_IPV4_NETMASK} | awk '/^Network/ {n=split($2, i, "/"); print i[2]};')
PUBLIC_IPV4_GATEWAY=$(curl -s http://169.254.169.254/metadata/v1/interfaces/public/0/ipv4/gateway)


kexec --initrd=${INITRD} -l ${VMLINUX} -f --command-line="quiet rancher.network.interfaces.eth0.address=${PUBLIC_IPV4}/${PUBLIC_IPV4_CIDR} rancher.network.interfaces.eth0.gateway=${PUBLIC_IPV4_GATEWAY} rancher.network.interfaces.eth0.dhcp=false rancher.cloud_init.datasources=[digitalocean] rancher.environment.installer=true"
